<template>
  <div class="site_table">

    <el-row style="top: 120px; left: 20%; z-index: 120">
      <el-select v-model="current_date.year"
                 placeholder="年份"
                 justify="center"
      >
        <el-option
            v-for="item in date_options.year"
            :key="item"
            :label="item"
            :value="item"
            @click="reload_table_data()"
        >
        </el-option>
      </el-select>
      <el-select v-model="current_date.season"
                 placeholder="季度"
                 justify="center"
                 style="margin-left: 20px">
        <el-option
            v-for="item in date_options.season"
            :key="item"
            :label="item"
            :value="item"
            @click="reload_table_data()"
        >
        </el-option>
      </el-select>
      <el-select v-model="current_date.week"
                 placeholder="周"
                 justify="center"
                 style="margin-left: 20px">

        <el-option
            v-for="item in date_options.week"
            :key="item"
            :label="item"
            :value="item"
            @click="reload_table_data()"
        >
        </el-option>
      </el-select>
    </el-row>
    <el-table id="data_table"
              :data="table_data"
              stripe
              border
              style="width: 60%;
              margin: auto" :row-style="{height: '80px'}">
      <el-table-column prop="time_label" label="时间"></el-table-column>

      <el-table-column v-for="column in columns"
                       :prop="column.prop"
                       :label="column.label">

        <template #default="scope">
          <div v-if="this.is_occupied(scope.row.time, scope.column.property)">
            {{ this.get_occupier(scope.row.time, scope.column.property) }}
            <el-button
                size="mini"
                type="danger"
                style="margin-left: 12px"
                icon="el-icon-delete"
                circle
                @click="on_click_remove_data_button(scope.row.time, scope.column.property)"/>
          </div>
          <div v-else>
            <el-button
                size="mini"
                type="primary"
                icon="el-icon-plus"
                circle
                @click="on_click_add_data_button(scope.row.time, scope.column.property)">
            </el-button>
          </div>

        </template>
      </el-table-column>


    </el-table>

    <el-dialog v-model="add_data_card_visible" title="添加使用记录" width="40%">
      <el-form ref="form"
               :model="form"
               label-width="120px"
               :rules="rules">
        <el-form-item label="申请人" prop="applicant">
          <el-input v-model="form.applicant"></el-input>
        </el-form-item>
        <el-form-item label="申请人学号" prop="applicant_id">
          <el-input v-model="form.applicant_id"></el-input>
        </el-form-item>
        <el-form-item label="事由" prop="reason">
          <el-input v-model="form.reason"></el-input>
        </el-form-item>

      </el-form>
      <el-row type="flex" justify="end">
        <el-button @click="on_cancel_add_data">取消</el-button>
        <el-button type="success" @click="on_summit_add_data()">确认</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "site_table",
  data() {
    return {
      site_code: 0,
      object_code: this.$store.state.object_code_dir.type2object_code.场地,
      date_options: {
        year: this.get_year_options(),
        season: ['春', '秋'],
        week: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
      },
      current_date: {
        year: new Date().getFullYear(),
        season: new Date().getMonth() + 1 > 7 ? '秋' : '春',
        week: this.get_current_week(),
        day: '',
        time: '',
      },
      columns: [ // 用v-for来遍历的
        {prop: 'monday', label: '星期一'},
        {prop: 'tuesday', label: '星期二'},
        {prop: 'wednesday', label: '星期三'},
        {prop: 'thursday', label: '星期四'},
        {prop: 'friday', label: '星期五'},
        {prop: 'saturday', label: '星期六'},
        {prop: 'sunday', label: '星期日'},
      ],
      table_data: [ // 表格一共有三行
        {
          time: 'morning',
          time_label: '上午',
        },
        {
          time: 'afternoon',
          time_label: '下午',
        },
        {
          time: 'evening',
          time_label: '晚上',
        }
      ],
      occupation_matrix: { // 从后端得到的
        morning: ["", "", "", "", "", "", ""],
        afternoon: ["", "", "", "", "", "", ""],
        evening: ["", "", "", "", "", "", ""],
      },
      add_data_card_visible: false,
      date: '',
      search_box_input: '',
      form: {
        applicant: '',
        applicant_id: '',
        reason: '',
        clear() {
          this.applicant = this.applicant_id = this.reason = ''
        }
      },
      rules: {
        applicant: [
          {required: true, trigger: 'blur', message: '请完成必填项'},
          {min: 1, max: 20, message: '长度在1到20个字符之间', trigger: 'blur'}
        ],
        applicant_id: [
          {min: 1, max: 20, message: '长度在1到20个字符之间', trigger: 'blur'}
        ],
        reason: [
          {min: 1, max: 20, message: '长度在1到20个字符之间', trigger: 'blur'}
        ],
      }
    }
  },
  computed: {},
  methods: {
    set_site_code(code) {
      this.site_code = code
    },
    get_year_options() {
      // 返回从2019年到现在的年份的列表
      let date = new Date()
      let ans = []
      let i = 2019
      for (; i <= date.getFullYear(); i++) {
        ans.push(i)
      }
      // 如果是12月了，就再把明年加进去
      if (date.getMonth() === 11) ans.push(i)
      return ans
    },
    get_current_week() {
      // 以9月1日作为秋学期第一周，3月1日作为春学期第一周
      // 如果算出来的周是负数，就返回1
      let date = new Date()
      let month = date.getMonth() + 1
      let startDate = ''
      let endDate = Date.parse('' + date.getFullYear() + '-'
          + (date.getMonth() + 1) + '-' + date.getDate())
      if (month > 7) {
        startDate = Date.parse('' + date.getFullYear() + '-9-1')
      } else {
        startDate = Date.parse('' + date.getFullYear() + '-3-1')
      }
      if (startDate > endDate) {
        return 1;
      }
      if (startDate == endDate) {
        return 1;
      }
      let days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
      return Math.ceil(days / 7);
    },
    is_occupied(time, day) {
      return this.occupation_matrix[time][this.day2num(day) - 1] !== ""
    },
    get_occupier(time, day) {
      return this.occupation_matrix[time][this.day2num(day) - 1]
    },
    day2num(day) {
      switch (day) {
        case 'monday':
          return 1;
        case 'tuesday':
          return 2;
        case 'wednesday':
          return 3;
        case 'thursday':
          return 4;
        case 'friday':
          return 5;
        case 'saturday':
          return 6;
        case 'sunday':
          return 7;
        default:
      }
    },
    on_click_add_data_button(time, day) {
      this.add_data_card_visible = true
      this.current_date.time = time // morning的形式
      this.current_date.day = this.day2num(day) // 转成数字
    },
    on_summit_add_data() {
      let data = {
        object_code: this.object_code, // 2表示正在添加成员
        key: this.$store.state.key,
        site_code: this.site_code,
        year: this.current_date.year,
        season: this.current_date.season,
        week: this.current_date.week,
        day: this.current_date.day,
        time: this.current_date.time,
        applicant: this.form.applicant,
        applicant_id: this.form.applicant_id,
        reason: this.form.reason
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          axios.post(this.$store.state.post_site_dir.add_data, data)
              .then((res) => {
                if (res.data.error_code !== 0) {
                  this.$alert("提交失败！请重新登录")
                  return
                }
                this.reload_table_data() // 刷新一下保证数据同步
                this.add_data_card_visible = false;
                this.form.clear()
              })
        }
      })
    },
    on_cancel_add_data() {
      this.add_data_card_visible = false
      this.form.clear()
    },

    on_click_remove_data_button(time, day) {
      // 弹出提示窗口确认以后再删除
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.post(this.$store.state.post_site_dir.remove_data,
            {
              key: this.$store.state.key,
              object_code: this.object_code,
              site_code: this.site_code,
              year: this.current_date.year,
              season: this.current_date.season,
              week: this.current_date.week,
              day: this.day2num(day),
              time: time
            })
            .then((res) => {
              if (res.data.error_code === 0) {
                this.reload_table_data()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                });
              } else {
                this.$message({
                  type: 'info',
                  message: '删除失败，请刷新网页重试！'
                });
              }
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    reload_table_data() {
      axios.post(this.$store.state.post_site_dir.query,
          {
            object_code: this.object_code,
            key: this.$store.state.key,
            site_code: this.site_code,
            year: this.current_date.year,
            season: this.current_date.season,
            week: this.current_date.week

          })
          .then((res) => {
            if (res.data.error_code !== 0) {
              this.$alert("没有权限！请重新登录")
            } else {
              // 把得到的数据转换成相应形式
              this.occupation_matrix = res.data.data
            }
          })
    },
    refresh_data() {
      this.reload_table_data()
    },
    click_search() {

    },
    origin_data2occupation_matrix() {
      // 用this.origin_data设置this.occupation_matrix
    }

  },
  watch: {
    site_code(newValue, oldValue) {
      this.refresh_data(newValue)
    }
  },
  mounted() {
    this.reload_table_data()
  },

}
</script>

<style scoped>
#data_table {
  top: 170px;
  z-index: 50;
}


#add_data_button {
  text-align: center;
  position: fixed;
  left: 10%;
  top: 100px;
  z-index: 110;
}

#search_box {
  display: flex;
  width: 300px;

  text-align: center;
  position: fixed;
  left: 40%;
  top: 100px;
  z-index: 110;
}

#search_bottom {
  height: 25px;
  width: 90px;
}

</style>